//
//  UIView+GaussianBlur.m
//  homework
//
//  Created by AW Technician on 16/1/6.
//  Copyright © 2016年 op. All rights reserved.
//

#import "UIView+GaussianBlur.h"
#import "UIWindow+AHKAdditions.h"
#import "UIImage+AHKAdditions.h"
#import <objc/runtime.h>

static const char associatedkeyDark;
static const char associatedkeyFrame;

@implementation UIView (GaussianBlur)

+ (UIView *)GaussianBlurViewWithDark:(BOOL)dark{
    return [UIView GaussianBlurViewWithFrame:[UIScreen mainScreen].bounds  withGBFrameBaseWindow:[UIScreen mainScreen].bounds withDark:dark];
}

+ (UIView *)GaussianBlurViewWithFrame:(CGRect)frame withGBFrameBaseWindow:(CGRect)GBframe withDark:(BOOL)dark{
    UIView *GBView = [[UIView alloc] initWithFrame:frame];
    UIImageView *ImageView = [[UIImageView alloc] initWithFrame:GBView.bounds];
    ImageView.tag = 100;
    ImageView.userInteractionEnabled = NO;
    UIImage *image;
    if (dark) {
        image = [[[UIApplication sharedApplication].keyWindow ahk_snapshot] ahk_applyDarkEffect];
    }else{
        image = [[[UIApplication sharedApplication].keyWindow ahk_snapshot] ahk_applyLightEffect];
    }
    objc_setAssociatedObject(GBView, &associatedkeyDark, @(dark), OBJC_ASSOCIATION_RETAIN);
    objc_setAssociatedObject(GBView, &associatedkeyFrame, NSStringFromCGRect(GBframe), OBJC_ASSOCIATION_RETAIN);
    CGImageRef CGImage = CGImageCreateWithImageInRect([image CGImage], CGRectMake(GBframe.origin.x*[UIScreen mainScreen].scale, GBframe.origin.y*[UIScreen mainScreen].scale, GBframe.size.width*[UIScreen mainScreen].scale, GBframe.size.height*[UIScreen mainScreen].scale));
    ImageView.image = [UIImage imageWithCGImage:CGImage];
    [GBView addSubview:ImageView];
    CGImageRelease(CGImage);
    return GBView;
}

- (void)updateGaussianBlurView{
    UIImageView *imageView = (UIImageView *)[self viewWithTag:100];
    UIImage *image;
    BOOL dark = [objc_getAssociatedObject(self, &associatedkeyDark) boolValue];
    if (dark) {
        image = [[[UIApplication sharedApplication].keyWindow ahk_snapshot] ahk_applyDarkEffect];
    }else{
        image = [[[UIApplication sharedApplication].keyWindow ahk_snapshot] ahk_applyLightEffect];
    }
    NSString *frameStr = objc_getAssociatedObject(self, &associatedkeyFrame);
    CGRect frame = CGRectFromString(frameStr);
    CGRect cropFrame =  CGRectMake(frame.origin.x*[UIScreen mainScreen].scale, frame.origin.y*[UIScreen mainScreen].scale, frame.size.width*[UIScreen mainScreen].scale, frame.size.height*[UIScreen mainScreen].scale);
    CGImageRef CGImage = CGImageCreateWithImageInRect([image CGImage], cropFrame);
    imageView.image = [UIImage imageWithCGImage:CGImage];
    CGImageRelease(CGImage);
}

@end
